﻿@using SmartStore
@using SmartStore.Core
@model ScheduleTaskModel
@{
	ViewBag.Title = T("Admin.System.ScheduleTasks.EditTask") + " - " + Model.Name;
	var returnUrl = ((string)ViewBag.ReturnUrl).NullEmpty();
}

@using (Html.BeginForm())
{
	@Html.AntiForgeryToken()
	@Html.HiddenFor(model => model.Id)
	@Html.Hidden("returnUrl", returnUrl)

	<div class="section-header">
		<div class="title">
			<i class="far fa-clock"></i>
			@ViewBag.Title
			<a href='@(returnUrl ?? Url.Action("List"))'>(@T("Common.Back"))</a>
		</div>
		<div class="options">
			<button type="submit" name="save" value="save" class="btn btn-warning">
				<i class="fa fa-check"></i>
				<span>@T("Admin.Common.Save")</span>
			</button>
			<button type="submit" name="save" value="save-continue" class="btn btn-secondary">
				<span>@T("Admin.Common.SaveContinue")</span>
			</button>
			@if (!Model.LastHistoryEntry.IsRunning)
			{
				<a href="@Model.ExecuteUrl" class="btn btn-secondary btn-to-danger">
					<i class='fa fa-play'></i>
					<span>@T("Admin.System.ScheduleTasks.RunNow")</span>
				</a>
			}
		</div>
	</div>
	
	@Html.ValidationSummary(false)

    @Html.SmartStore().TabStrip().Name("schedule-task-edit").Style(TabsStyle.Material).Items(x =>
    {
        x.Add().Text(T("Common.General").Text).Content(TabGeneral()).Selected(true);
        x.Add().Text(T("Common.History").Text).Content(TabHistory());
    
        EngineContext.Current.Resolve<IEventPublisher>().Publish(new TabStripCreated(x, "schedule-task-edit", this.Html, this.Model));
    })
}

@helper TabGeneral()
{
	<table class="adminContent">
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(model => model.Name)
			</td>
			<td class="adminData">
				@Html.EditorFor(model => model.Name)
				@Html.ValidationMessageFor(model => model.Name)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(model => model.RunPerMachine)
			</td>
			<td class="adminData">
				<div class="form-control-plaintext">
					@T(Model.RunPerMachine ? "Common.Yes" : "Common.No")
				</div>
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(model => model.Enabled)
			</td>
			<td class="adminData">
				@Html.EditorFor(model => model.Enabled)
				@Html.ValidationMessageFor(model => model.Enabled)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(model => model.StopOnError)
			</td>
			<td class="adminData">
				@Html.EditorFor(model => model.StopOnError)
				@Html.ValidationMessageFor(model => model.StopOnError)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(model => model.LastHistoryEntry.StartedOn)
			</td>
			<td class="adminData">
				<div class="form-control-plaintext">
					@if (Model.LastHistoryEntry.Id != 0)
					{
						@Html.DisplayFor(model => model.LastHistoryEntry.StartedOn)
					}
					else
					{
						@T("Common.Never")
					}
				</div>
			</td>
		</tr>
		@if (Model.LastHistoryEntry.Duration.HasValue())
		{
			<tr>
				<td class="adminTitle">
					@Html.SmartLabelFor(model => model.LastHistoryEntry.Duration)
				</td>
				<td class="adminData">
					<div class="form-control-plaintext">
						@Html.DisplayFor(model => model.LastHistoryEntry.Duration)
					</div>
				</td>
			</tr>
		}
		@if (Model.LastHistoryEntry.Error.HasValue())
		{
			<tr>
				<td class="adminTitle text-danger">
					@Html.SmartLabelFor(model => model.LastHistoryEntry.Error)
				</td>
				<td class="adminData">
					<div class="form-control-plaintext">
                        <pre class="prettyprint xlang-java mt-1 mb-0" style="max-height: 200px; white-space: pre-wrap;">@Html.DisplayFor(model => model.LastHistoryEntry.Error)</pre>
					</div>
				</td>
			</tr>
			if (Model.LastHistoryEntry.SucceededOn.HasValue && Model.LastHistoryEntry.SucceededOn != Model.LastHistoryEntry.FinishedOn)
			{
				<tr>
					<td class="adminTitle">
						@Html.SmartLabelFor(model => model.LastHistoryEntry.SucceededOn)
					</td>
					<td class="adminData">
						<div class="form-control-plaintext">
							@Html.DisplayFor(model => model.LastHistoryEntry.SucceededOn)
						</div>
					</td>
				</tr>
			}
		}
		@if (Model.NextRun.HasValue)
		{
			<tr>
				<td class="adminTitle">
					@Html.SmartLabelFor(model => model.NextRun)
				</td>
				<td class="adminData">
					<div class="form-control-plaintext">
						@Html.DisplayFor(model => model.NextRun)
					</div>
				</td>
			</tr>
		}
		<tr>
			<td class="adminTitle">
				@Html.SmartLabelFor(model => model.CronExpression)
			</td>
			<td class="adminData">
				@Html.EditorFor(model => model.CronExpression )
				@Html.ValidationMessageFor(model => model.CronExpression)
			</td>
		</tr>
		<tr>
			<td class="adminTitle">&nbsp;</td>
			<td class="adminData">
				<div class="muted">@T("Admin.System.ScheduleTasks.CronHelp", GenerateHelpUrl(HelpTopic.CronExpressions))</div>
			</td>
		</tr>
		<tr>
			<td class="adminTitle">&nbsp;</td>
			<td class="adminData">
				<div id="future-schedules"></div>
			</td>
		</tr>
	</table>
}

@helper TabHistory()
{
    <div class="alert alert-info alert-dismissible">
        @Html.Raw((string)ViewBag.HistoryCleanupNote)
        <button type="button" class="close" data-dismiss="alert">&times;</button>
    </div>

    <script type="text/javascript">
	    function OnTaskHistoryGridRowDataBound(e) {
		    if (e.dataItem.IsRunning) {
                $(e.row).find('td:last .t-grid-delete').remove();
		    }
	    }
    </script>
    <div>
		@(Html.Telerik().Grid<ScheduleTaskHistoryModel>()
            .Name("schedule-task-history-grid")
            .DataKeys(keys =>
            {
                keys.Add(x => x.Id).RouteKey("id");
            })
            .DataBinding(dataBinding =>
            {
                dataBinding.Ajax()
                    .Select("HistoryList", "ScheduleTask", new { taskId = Model.Id })
                    .Delete("DeleteHistoryEntry", "ScheduleTask");
            })
			.ClientEvents(e =>
			{
				e.OnRowDataBound("OnTaskHistoryGridRowDataBound");
			})
            .Columns(columns =>
            {
                columns.Bound(x => x.StartedOn)
                    .Title(T("Common.ExecutedOn"))
                    .Width(260)
                    .ClientTemplate(
                        "<div>" +
                        "<div><#= StartedOnString #></div>" +
                        "<div class='muted'><#= StartedOnPretty #></div>" +
                        "</div>");
                columns.Bound(x => x.FinishedOn)
                    .Title(T("Common.FinishedOn"))
                    .Width(260)
                    .ClientTemplate(
                        "<div>" +
                        "<div><#= FinishedOnString #></div>" +
                        "<div class='muted'><#= FinishedOnPretty #></div>" +
                        "</div>");
                columns.Bound(x => x.Duration)
                    .Width(260);
                columns.Bound(x => x.Succeeded)
                    .ClientTemplate(
                        "<# if(Succeeded){ #>" + @Html.SymbolForBool("Succeeded") + "<span class='ml-1'>" + T("Common.Succeeded") + "</span><# } #>" +
                        "<# if(!Succeeded){ #><div class='text-danger font-weight-medium'>" + T("Common.Error") + ":</div><pre class='prettyprint xlang-java mt-1 mb-0' style='max-height: 200px; white-space: pre-wrap;'><strong>" + T("Common.Error") + ": </strong> <span><#= Error #></span></pre><# } #>");
                columns.Bound(x => x.MachineName);
                columns.Command(commands =>
                {
                    commands.Delete().Localize(T);
                })
                .Width(200)
                .HtmlAttributes(new { align = "right" });
            })
            .Pageable(settings => settings.PageSize((int)ViewBag.GridPageSize).Position(GridPagerPosition.Both))
            .PreserveGridState()
            .EnableCustomBinding(true))
    </div>
}

<script>
	$(function () {
		$('#@Html.FieldIdFor(m => m.CronExpression)').on('input propertychange paste', function (e) {
			getFutureSchedules.apply(this);
		});

		getFutureSchedules.apply($('#@Html.FieldIdFor(m => m.CronExpression)')[0]);

		function getFutureSchedules() {
			var input = $(this);

			if (!input.val().length)
				return;

			$.ajax({
				cache: false,
				type: 'POST',
				url: '@Url.Action("FutureSchedules")',
				data: { expression: input.val() },
				success: function (data) {
					$('#future-schedules').html(data);
				},
				error: function (xhr, ajaxOptions, thrownError) {
				}
			});
		}
	});
</script>
